import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useSeatStore } from './seat'

export const useOrderStore = defineStore('order', () => {
  // 状态
  const orders = ref([])
  const currentOrder = ref(null)
  const loading = ref(false)
  
  // 计算属性
  const activeOrders = computed(() => {
    return orders.value.filter(order => 
      ['pending', 'confirmed', 'in_progress'].includes(order.status)
    )
  })
  
  const historyOrders = computed(() => {
    return orders.value.filter(order => 
      ['completed', 'cancelled'].includes(order.status)
    )
  })
  
  const todayOrders = computed(() => {
    const today = new Date().toDateString()
    return orders.value.filter(order => 
      new Date(order.createdAt).toDateString() === today
    )
  })
  
  const totalSpent = computed(() => {
    return orders.value
      .filter(order => order.status === 'completed')
      .reduce((total, order) => total + order.totalAmount, 0)
  })
  
  const totalSaved = computed(() => {
    return orders.value
      .filter(order => order.status === 'completed')
      .reduce((total, order) => total + (order.discountAmount || 0), 0)
  })
  
  // 方法
  const fetchOrders = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 这里应该是真实的API调用
      // const response = await uni.request({
      //   url: '/api/orders',
      //   method: 'GET'
      // })
      
      // 查找当前进行中的订单
      currentOrder.value = orders.value.find(order => order.status === 'in_progress')
      
      return { success: true }
    } catch (error) {
      console.error('获取订单失败:', error)
      return { success: false, message: '获取订单失败' }
    } finally {
      loading.value = false
    }
  }
  
  const createOrder = async (orderData) => {
    try {
      loading.value = true
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      
      const newOrder = {
        id: Date.now(),
        seatId: orderData.seatId,
        seatNumber: orderData.seatNumber || `座位${orderData.seatId}`,
        startTime: orderData.startTime,
        endTime: orderData.endTime,
        duration: orderData.duration,
        hourlyRate: orderData.hourlyRate || 6,
        baseAmount: orderData.baseAmount || (orderData.duration * 6),
        discountAmount: orderData.discountAmount || 0,
        totalAmount: orderData.totalAmount,
        status: 'confirmed',
        paymentStatus: 'paid',
        paymentMethod: orderData.paymentMethod || 'wechat',
        couponId: orderData.couponId,
        createdAt: new Date(),
        updatedAt: new Date()
      }
      
      // 如果是立即开始的订单，设置为进行中
      const now = new Date()
      if (new Date(orderData.startTime) <= now) {
        newOrder.status = 'in_progress'
        currentOrder.value = newOrder
        
        // 更新座位状态
        const seatStore = useSeatStore()
        seatStore.updateSeatStatus(orderData.seatId, 'occupied', orderData.endTime)
      }
      
      orders.value.unshift(newOrder)
      
      return { success: true, data: newOrder }
    } catch (error) {
      console.error('创建订单失败:', error)
      return { success: false, message: '创建订单失败' }
    } finally {
      loading.value = false
    }
  }
  
  const cancelOrder = async (orderId) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const order = orders.value.find(o => o.id === orderId)
      if (order) {
        order.status = 'cancelled'
        order.updatedAt = new Date()
        
        // 如果取消的是当前订单，清除当前订单并释放座位
        if (currentOrder.value && currentOrder.value.id === orderId) {
          currentOrder.value = null
          
          // 释放座位
          const seatStore = useSeatStore()
          seatStore.updateSeatStatus(order.seatId, 'available')
        }
      }
      
      return { success: true }
    } catch (error) {
      console.error('取消订单失败:', error)
      return { success: false, message: '取消订单失败' }
    }
  }
  
  const completeOrder = async (orderId) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const order = orders.value.find(o => o.id === orderId)
      if (order) {
        order.status = 'completed'
        order.actualEndTime = new Date()
        order.updatedAt = new Date()
        
        // 清除当前订单并释放座位
        if (currentOrder.value && currentOrder.value.id === orderId) {
          currentOrder.value = null
          
          // 释放座位
          const seatStore = useSeatStore()
          seatStore.updateSeatStatus(order.seatId, 'available')
        }
      }
      
      return { success: true }
    } catch (error) {
      console.error('结束订单失败:', error)
      return { success: false, message: '结束订单失败' }
    }
  }
  
  const extendOrder = async (orderId, additionalHours) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const order = orders.value.find(o => o.id === orderId)
      if (order) {
        const additionalCost = additionalHours * order.hourlyRate
        
        order.duration += additionalHours
        order.endTime = new Date(new Date(order.endTime).getTime() + additionalHours * 60 * 60 * 1000)
        order.totalAmount += additionalCost
        order.updatedAt = new Date()
        
        // 更新座位占用时间
        const seatStore = useSeatStore()
        seatStore.updateSeatStatus(order.seatId, 'occupied', order.endTime)
      }
      
      return { success: true, additionalCost }
    } catch (error) {
      console.error('续费失败:', error)
      return { success: false, message: '续费失败' }
    }
  }
  
  const getOrderById = (orderId) => {
    return orders.value.find(order => order.id === orderId)
  }
  
  const updateOrderStatus = (orderId, status) => {
    const order = orders.value.find(o => o.id === orderId)
    if (order) {
      order.status = status
      order.updatedAt = new Date()
      
      // 更新当前订单状态
      if (currentOrder.value && currentOrder.value.id === orderId) {
        if (status === 'in_progress') {
          currentOrder.value = order
        } else if (['completed', 'cancelled'].includes(status)) {
          currentOrder.value = null
        }
      }
    }
  }
  
  const getRemainingTime = (order) => {
    if (!order || order.status !== 'in_progress') return 0
    
    const now = new Date()
    const endTime = new Date(order.endTime)
    const remaining = endTime.getTime() - now.getTime()
    
    return Math.max(0, Math.floor(remaining / 1000)) // 返回剩余秒数
  }
  
  const formatRemainingTime = (seconds) => {
    if (seconds <= 0) return '00:00:00'
    
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  
  // 获取订单统计
  const getOrderStats = () => {
    const stats = {
      total: orders.value.length,
      active: activeOrders.value.length,
      completed: historyOrders.value.filter(o => o.status === 'completed').length,
      cancelled: historyOrders.value.filter(o => o.status === 'cancelled').length,
      totalSpent: totalSpent.value,
      totalSaved: totalSaved.value,
      averageSession: 0
    }
    
    // 计算平均使用时长
    const completedOrders = orders.value.filter(o => o.status === 'completed')
    if (completedOrders.length > 0) {
      const totalDuration = completedOrders.reduce((sum, order) => sum + order.duration, 0)
      stats.averageSession = Math.round(totalDuration / completedOrders.length * 10) / 10
    }
    
    return stats
  }
  
  // 初始化模拟订单数据
  const initMockOrders = () => {
    const mockOrders = [
      {
        id: 1001,
        seatId: 15,
        seatNumber: 'B7',
        startTime: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2小时前开始
        endTime: new Date(Date.now() + 1 * 60 * 60 * 1000), // 1小时后结束
        duration: 3,
        hourlyRate: 6,
        baseAmount: 18,
        discountAmount: 3,
        totalAmount: 15,
        status: 'in_progress',
        paymentStatus: 'paid',
        paymentMethod: 'wechat',
        createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000),
        updatedAt: new Date()
      },
      {
        id: 1002,
        seatId: 32,
        seatNumber: 'D8',
        startTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
        endTime: new Date(Date.now() - 22 * 60 * 60 * 1000),
        actualEndTime: new Date(Date.now() - 22 * 60 * 60 * 1000),
        duration: 2,
        hourlyRate: 6,
        baseAmount: 12,
        discountAmount: 2,
        totalAmount: 10,
        status: 'completed',
        paymentStatus: 'paid',
        paymentMethod: 'alipay',
        createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 22 * 60 * 60 * 1000)
      },
      {
        id: 1003,
        seatId: 58,
        seatNumber: 'H2',
        startTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
        endTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000),
        actualEndTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000),
        duration: 4,
        hourlyRate: 12,
        baseAmount: 48,
        discountAmount: 8,
        totalAmount: 40,
        status: 'completed',
        paymentStatus: 'paid',
        paymentMethod: 'balance',
        createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000)
      }
    ]
    
    orders.value = mockOrders
    currentOrder.value = mockOrders.find(order => order.status === 'in_progress')
    
    console.log(`初始化了 ${mockOrders.length} 个订单`)
  }
  
  return {
    // 状态
    orders,
    currentOrder,
    loading,
    
    // 计算属性
    activeOrders,
    historyOrders,
    todayOrders,
    totalSpent,
    totalSaved,
    
    // 方法
    fetchOrders,
    createOrder,
    cancelOrder,
    completeOrder,
    extendOrder,
    getOrderById,
    updateOrderStatus,
    getRemainingTime,
    formatRemainingTime,
    getOrderStats,
    initMockOrders
  }
})
